package com.jp.fm.service;

import java.util.Collections;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import com.jp.fm.dao.BudgetDao;
import com.jp.fm.dao.TransactionDao;
import com.jp.fm.data.Budget;
import com.jp.fm.data.Category;
import com.jp.fm.data.Transaction;

public class BudgetService {

	private TransactionService transactionService = null;
	private TransactionDao transactionDao = null;
	private BudgetDao budgetDao = null;

	public List<Budget> findBudgetList(final Date startDate,
			final Date endDate, final List<String> alerts) {
		List<Budget> budgetList = budgetDao.findByDate(startDate);

		// Set the current amount for each Budget item
		for (Iterator<Budget> iterator = budgetList.iterator(); iterator
				.hasNext();) {
			Budget budget = iterator.next();

			Category cat = budget.getCategory();

			List<Transaction> trans = transactionDao.findByAny(cat, startDate,
					endDate, null, null, null);

			Float categoryAmount = transactionService
					.calculateTransactionsTotal(trans, cat);

			budget.setCurrentAmount(categoryAmount);

			if (categoryAmount > budget.getAmount()) {
				alerts.add("Over budget for the "
						+ "<a class=\"click-link\" url=\"/fm/secured/ShowTransactions?categoryThisMonth="
						+ budget.getCategory().getName() + "\">"
						+ budget.getCategory().getName()
						+ "</a> category this month");
			}
		}
		Collections.sort(budgetList);

		return budgetList;
	}

	public final void setTransactionService(
			final TransactionService transactionService) {
		this.transactionService = transactionService;
	}

	public final void setTransactionDao(final TransactionDao transactionDao) {
		this.transactionDao = transactionDao;
	}

	public final void setBudgetDao(final BudgetDao budgetDao) {
		this.budgetDao = budgetDao;
	}
}
